package com.bawei.module_mall

import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.View
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseActivity
import com.bawei.module_mall.databinding.ActivityShopDetailBinding
import com.bawei.module_mall.http.viewModel.ShopViewModel
import android.os.Bundle
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.lifecycleScope
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_mall.http.intent.ShopIntent
import kotlinx.coroutines.launch
import com.bawei.module_mall.http.state.ShopState
import com.bumptech.glide.Glide
import android.widget.TextView
import android.os.Handler
import android.os.Looper
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import android.widget.LinearLayout
import com.google.android.material.bottomsheet.BottomSheetDialog
import android.widget.RadioGroup
import android.widget.GridLayout
import android.widget.Button
import com.bawei.module_mall.model.ShopDetailModel
import android.widget.RadioButton
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.bawei.lib_net.common.ConstantValue
import com.bawei.lib_net.msgbus.LiveDataBus
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.module_mall.model.AddShopModel
import kotlin.text.isNullOrEmpty
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.module_mall.model.CommentRecord
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.Toast
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMVideo

@Route(path = Router.Ui.SHOP_DETAIL_ACTIVITY)
class ShopDetailActivity : BaseActivity() {
    private val binding by lazy { ActivityShopDetailBinding.inflate(layoutInflater) }
    private val viewModel: ShopViewModel by viewModels()
    lateinit var simpleVideoEntity: ShopDetailModel
    // 请求数据
    @Autowired
    @JvmField
    var shopId: Int = -1
    // Tab标题
    private val tabTitles = listOf("商品", "评价", "详情")
    // section对应的ViewId
    private val sectionIds = listOf(
        R.id.section_goods,
        R.id.section_comment,
        R.id.section_detail
    )

    // 收藏状态
    private var isCollected = false
    private var currentGoodsId = 0
    private var isInitialCheck = true // 标记是否是初始检查

    // 购物车数量
    private var cartCount = 0

    // --- 内存泄漏修复相关 ---
    private val handler = Handler(Looper.getMainLooper())
    private val bannerAdapter = BannerAdapter(emptyList())
    private val bannerRunnable = object : Runnable {
        override fun run() {
            val count = bannerAdapter.itemCount
            if (count > 1) {
                val next = (binding.bannerViewPager.currentItem + 1) % count
                binding.bannerViewPager.setCurrentItem(next, true)
            }
            handler.postDelayed(this, 3000)
        }
    }
    private var goodsDialog: BottomSheetDialog? = null
    // --- end ---

    /**
     * 清洗 URL 中的特殊符号（如转义符、引号、方括号等）
     */
    fun cleanImageUrl(rawUrl: String): String {
        return rawUrl
            .replace("\"", "")       // 去掉所有引号（包括转义符 \"）
            .replace("[", "")        // 去掉左方括号
            .replace("]", "")        // 去掉右方括号
            .trim()                  // 去掉首尾空格
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this) // 必须加
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        // 设置Tab
        tabTitles.forEach { binding.tabLayout.addTab(binding.tabLayout.newTab().setText(it)) }
        // 顶部栏初始完全透明，Tab隐藏，左右控件可见
        binding.topBar.setBackgroundColor(Color.argb(0, 255, 255, 255)) // 完全透明
        binding.tabLayout.alpha = 0f
        binding.tabLayout.visibility = View.GONE
        binding.ivBack.alpha = 1f
        binding.ivShare.alpha = 1f
        binding.imgShop.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.SHOP_ACTIVITY).navigation()
        }
        // 先禁用分享按钮，等数据加载成功后再启用
        binding.ivShare.isEnabled = false
        binding.ivShare.setOnClickListener {
            if (!::simpleVideoEntity.isInitialized) {
                Toast.makeText(this, "数据未加载完成，无法分享", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val umVideo = UMVideo(simpleVideoEntity.mainImgUrl)
            umVideo.setTitle(simpleVideoEntity.title)
            umVideo.setThumb(UMImage(this@ShopDetailActivity,simpleVideoEntity.mainImgUrl))
            umVideo.setDescription(simpleVideoEntity.params)
            ShareAction(this@ShopDetailActivity)
                .withText("hello")
                .withMedia(umVideo)
                .setPlatform(SHARE_MEDIA.QQ) //传入平台
                .setCallback(object : UMShareListener {
                    override fun onStart(share_media: SHARE_MEDIA) {}
                    override fun onResult(share_media: SHARE_MEDIA) {}
                    override fun onError(share_media: SHARE_MEDIA, throwable: Throwable) {
                        Toast.makeText(this@ShopDetailActivity, "分享失败", Toast.LENGTH_SHORT).show()
                    }
                    override fun onCancel(share_media: SHARE_MEDIA) {}
                }) //回调监听器
                .open()
        }
        // 轮播图适配器
        binding.bannerViewPager.adapter = bannerAdapter
        binding.bannerViewPager.offscreenPageLimit = 1
        // 自动轮播（可选）
        handler.postDelayed(bannerRunnable, 3000)
        // Tab点击跳转
        binding.tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                val targetView = binding.llContent.findViewById<View>(sectionIds[tab.position])
                targetView?.let {
                    val y = it.top + binding.llContent.top
                    binding.nestedScrollView.smoothScrollTo(0, y)
                }
            }
            override fun onTabUnselected(tab: TabLayout.Tab) {}
            override fun onTabReselected(tab: TabLayout.Tab) {}
        })

        // 滚动监听，顶部渐变、Tab高亮
        binding.nestedScrollView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
            // 顶部渐变逻辑
            val location = IntArray(2)
            binding.tabAnchor.getLocationOnScreen(location)
            val anchorY = location[1]
            val topBarHeight = binding.topBar.height
            val statusBarHeight = getStatusBarHeight()
            val threshold = topBarHeight + statusBarHeight
            val maxOffset = 300f // 渐变最大距离
            val offset = (threshold - anchorY).coerceAtLeast(0)
            val alpha = (offset / maxOffset).coerceIn(0f, 1f) // 0=透明, 1=不透明

            // 顶部栏背景
            val bgColor = Color.argb((alpha * 255).toInt(), 255, 255, 255)
            binding.topBar.setBackgroundColor(bgColor)

            // Tab和字段的显示与隐藏，透明度同步
            if (alpha > 0.05f) {
                binding.tabLayout.visibility = View.VISIBLE
                binding.tabLayout.alpha = alpha
            } else {
                binding.tabLayout.alpha = 0f
                binding.tabLayout.visibility = View.GONE
            }

            // 左右控件单独处理：滑动时透明度渐变，顶部时完全可见
            val sideAlpha = if (alpha > 0.05f) alpha else 1f
            binding.ivBack.alpha = sideAlpha
            binding.ivShare.alpha = sideAlpha

            // Tab高亮逻辑
            var current = 0
            for (i in sectionIds.indices) {
                val v = binding.llContent.findViewById<View>(sectionIds[i])
                if (v != null && v.top + binding.llContent.top - scrollY <= binding.tabLayout.top + 10) {
                    current = i
                }
            }
            if (binding.tabLayout.selectedTabPosition != current) {
                binding.tabLayout.getTabAt(current)?.select()
            }
        })

        // 返回按钮
        binding.ivBack.setOnClickListener { finish() }
        
        // 分享按钮（可自定义分享逻辑）

        // 1. 获取shopId
        if (shopId != -1) {
            viewModel.intents.trySend(ShopIntent.GetShopDetail(shopId))
        }
        // 设置收藏按钮点击事件
        binding.layoutShopInfo.imgCollect.setOnClickListener {
            viewModel.intents.trySend(ShopIntent.ToggleCollect(shopId))
        }

        // 页面启动时请求购物车数量
        lifecycleScope.launch {
            viewModel.intents.send(ShopIntent.GetShopNumber)
        }
        lifecycleScope.launch {
            viewModel.intents.send(ShopIntent.GetComment(shopId,1,10))
        }
        // 监听全局购物车数量变化
        LiveDataBus.with<Int>("cart_count").observe(this) { count ->
            updateCartBadge(count)
        }

        lifecycleScope.launch {
            // 先检查收藏状态
            viewModel.intents.send(ShopIntent.CheckCollect(shopId))
            // 再获取商品详情
            viewModel.intents.send(ShopIntent.GetShopDetail(shopId))
            viewModel.state.collect { state ->
                when (state) {
                    is ShopState.ShopDetailSuccess -> {
                        try {
                            val detail = state.data
                            if (detail == null) {
                                // 隐藏原有内容，动态添加空布局
                                binding.root.visibility = View.GONE
                                val emptyView = layoutInflater.inflate(R.layout.layout_search_empty, null)
                                addContentView(emptyView, ViewGroup.LayoutParams(
                                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
                                ))
                                return@collect
                            }
                            // 赋值 simpleVideoEntity 并启用分享按钮
                            simpleVideoEntity = detail
                            binding.ivShare.isEnabled = true
                            // 1. 清洗所有图片 URL
                            val cleanUrls = detail.posterUll.map { rawUrl ->
                                cleanImageUrl(rawUrl)
                            }
                            // 2. 更新 BannerAdapter 的数据
                            bannerAdapter.update(cleanUrls)
//                            // 3. （可选）重新启动轮播
//                            binding.bannerViewPager.currentItem = 0
//                            bannerRunnable.let {
//                                handler.removeCallbacks(it)
//                                handler.postDelayed(it, 3000)
//                            }
                            // 2. 商品信息区
                            binding.layoutShopInfo.tvTitle.text = detail.title
                            binding.layoutShopInfo.tvPrice.text = "￥${detail.purchasePrice}"
//                            // 3. 商品内容
                            binding.sectionGoods.removeAllViews()
                            val goodsView = layoutInflater.inflate(R.layout.layout_goods_comment, binding.sectionGoods, false)
                            binding.sectionGoods.addView(goodsView)
                            // 4.
                            binding.sectionComment.removeAllViews()
                            val commentView = layoutInflater.inflate(R.layout.layout_goods_contents, binding.sectionComment, false)
                            binding.sectionComment.addView(commentView)
                            // 5. 详情内容
                            binding.sectionDetail.removeAllViews()
                            val detailView = layoutInflater.inflate(R.layout.layout_goods_detail, binding.sectionDetail, false)
                            val imgContainer = detailView.findViewById<LinearLayout>(R.id.img_container)
                            val cleanUrl = detail.detailUrl.flatMap { raw ->
                                raw.replace("[", "")
                                    .replace("]", "")
                                    .replace("\\\"", "")
                                    .split(",")
                                    .map { it.trim().replace("\"", "") }
                                    .filter { it.startsWith("http") }
                            }
                            LoggerUtils.d("img", cleanUrls.toString())
                            for (url in cleanUrl) {
                                val imageView = ImageView(this@ShopDetailActivity)
                                imageView.layoutParams = LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT
                                     // 可根据需要调整高度
                                ).apply {
                                    setMargins(0, 16, 0, 16)
                                }
                                imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                                Glide.with(this@ShopDetailActivity).load(url).into(imageView)
                                imgContainer.addView(imageView)
                            }
                            binding.sectionDetail.addView(detailView)

                            // 修改底部加入购物车按钮点击事件
                            binding.btnAddCart.setOnClickListener {
                                // 只弹出弹窗，不发起网络请求
                                showGoodsSpecDialog(detail)
                            }
                            // 修改底部立即购买按钮点击事件
                            binding.btnBuyNow.setOnClickListener {
                                showGoodsSpecDialog(detail)
                            }
                        } catch (e: Exception) {
                            binding.root.visibility = View.GONE
                            val emptyView = layoutInflater.inflate(R.layout.layout_search_empty, null)
                            addContentView(emptyView, ViewGroup.LayoutParams(
                                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
                            ))
                        }
                    }
                    is ShopState.CheckCollectResult -> {
                        // 更新收藏状态UI
                        isCollected = state.isCollected
                        updateCollectUI()
                        // 如果不是初始检查，说明是切换收藏后的检查，显示相应提示
                        if (!isInitialCheck && state.goodsId == currentGoodsId) {
                            if (isCollected) {
                                showMsg("收藏成功")
                            } else {
                                showMsg("取消收藏成功")
                            }
                        }
                        // 标记初始检查完成
                        isInitialCheck = false
                    }
                    is ShopState.Error -> {
                        binding.root.visibility = View.GONE
                        val emptyView = layoutInflater.inflate(R.layout.layout_search_empty, null)
                        addContentView(emptyView, ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
                        ))
                    }
                    is ShopState.GetShopNumberSuccess -> {
                        updateCartBadge(state.data)
                    }
                    is ShopState.GetCommentSuccess -> {
                        val commentList = state.data?.records ?: emptyList()
                        // 设置评论数量
                        val commentCountView = findViewById<TextView>(R.id.comment_number)
                        commentCountView?.text = "${commentList.size}条评论"
                        // 渲染评论列表
                        val commentRecyclerView = findViewById<RecyclerView>(R.id.rv_comment)
                        commentRecyclerView?.layoutManager = LinearLayoutManager(this@ShopDetailActivity)
                        commentRecyclerView?.adapter = CommentAdapter(commentList)
                    }
                    else -> {}
                }
            }
        }
        // 监听token失效
        LiveDataBus.with<Int>(ConstantValue.NET_STATE).observe(this) { code ->
            if (code == 401 || code == 40103) {
                AuthMMKV.token = ""
                // 跳转到登录页
                ARouter.getInstance().build(Router.Ui.USER_ACTIVITY).navigation()
                showMsg("登录失效，请重新登录")
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
        goodsDialog?.dismiss()
        goodsDialog = null
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }

    // 获取状态栏高度
    private fun getStatusBarHeight(): Int {
        var result = 0
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

    // 更新收藏按钮UI状态
    private fun updateCollectUI() {
        val heartImageView = binding.layoutShopInfo.imgCollect.findViewById<ImageView>(R.id.iv_heart)
        val collectTextView = binding.layoutShopInfo.imgCollect.findViewById<TextView>(R.id.tv_collect)

        if (isCollected) {
            // 已收藏状态：红色爱心
            heartImageView.setImageResource(R.drawable.like_24_red)
            collectTextView.setTextColor(ContextCompat.getColor(this, R.color.red))
        } else {
            // 未收藏状态：灰色爱心
            heartImageView.setImageResource(R.drawable.like_24)
            collectTextView.setTextColor(Color.GRAY)
        }
    }

    // 轮播图Adapter
    inner class BannerAdapter(private var data: List<String>) : RecyclerView.Adapter<BannerAdapter.BannerViewHolder>() {

        inner class BannerViewHolder(val imageView: ImageView) : RecyclerView.ViewHolder(imageView)
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BannerViewHolder {
            val iv = ImageView(parent.context)
            iv.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            iv.scaleType = ImageView.ScaleType.CENTER_CROP
            return BannerViewHolder(iv)
        }

        override fun onBindViewHolder(holder: BannerViewHolder, position: Int) {
            val cleanUrl = data[position]
            // 确保 data[position] 是纯净 URL，无多余引号/转义
            Glide.with(holder.imageView).load(cleanUrl).into(holder.imageView)
        }
        override fun getItemCount() = data.size
        fun update(newData: List<String>) {
            data = newData
            notifyDataSetChanged()
        }
    }

    // 商品规格弹窗
    private fun showGoodsSpecDialog(detail: ShopDetailModel) {
        val dialogView = layoutInflater.inflate(R.layout.dialog_goods_spec, null)
        goodsDialog = BottomSheetDialog(this)
        goodsDialog?.setContentView(dialogView)

        // 绑定控件
        val ivGoods = dialogView.findViewById<ImageView>(R.id.iv_goods)
        val tvPrice = dialogView.findViewById<TextView>(R.id.tv_price)
        val tvCode = dialogView.findViewById<TextView>(R.id.tv_code)
        val rgColor = dialogView.findViewById<RadioGroup>(R.id.rg_color)
        val glSize = dialogView.findViewById<GridLayout>(R.id.gl_size)
        val ivMinus = dialogView.findViewById<ImageView>(R.id.iv_minus)
        val ivPlus = dialogView.findViewById<ImageView>(R.id.iv_plus)
        val tvCount = dialogView.findViewById<TextView>(R.id.tv_count)
        val btnAddCart = dialogView.findViewById<Button>(R.id.btn_add_cart)
        val btnBuyNow = dialogView.findViewById<Button>(R.id.btn_buy_now)
        val ivClose = dialogView.findViewById<ImageView>(R.id.iv_close)
        val carNames = detail.skuList.map { it.skuName }
        val colorMap = mutableMapOf<String, String>() // 颜色名->图片url
        var selectedColor = colorMap.keys.firstOrNull() ?: ""
        var selectedCarName = carNames.getOrNull(0) ?: ""
        // 在showGoodsSpecDialog方法中，找到弹窗布局的已选和参数TextView
        val tvSelected = dialogView.findViewById<TextView?>(R.id.tv_selected)
        // 定义一个方法用于刷新已选和参数信息
        fun updateSelectedAndParams() {
            val selectedInfo = "已选：$selectedColor / $selectedCarName "
            tvSelected?.text = selectedInfo
            // 查找当前sku
            val sku = detail.skuList.find { sku ->
                val color = sku.attrs.split(",").firstOrNull()?.trim() ?: ""
                sku.skuName == selectedCarName && color == selectedColor
            }
        }
        // 初始化时刷新
        updateSelectedAndParams()

        // 车型名列表（替换尺码）

        glSize.removeAllViews()
        carNames.forEachIndexed { idx, name ->
            val btn = TextView(this)
            btn.text = name
            btn.setPadding(24, 12, 24, 12)
            btn.setBackgroundResource(R.drawable.bg_size_selector)
            btn.setTextColor(if (idx == 0) ContextCompat.getColor(this, R.color.red) else Color.BLACK)
            btn.isSelected = idx == 0
            btn.setOnClickListener {
                for (i in 0 until glSize.childCount) {
                    val child = glSize.getChildAt(i) as TextView
                    child.isSelected = false
                    child.setTextColor(Color.BLACK)
                }
                btn.isSelected = true
                btn.setTextColor(ContextCompat.getColor(this, R.color.red))
                selectedCarName = name
                // 切换车型时同步刷新价格和图片
                val sku = detail.skuList.find { sku ->
                    val color = sku.attrs.split(",").firstOrNull()?.trim() ?: ""
                    sku.skuName == selectedCarName && color == selectedColor
                }
                if (sku != null) {
                    tvPrice.text = "￥${sku.purchasePrice}"
                    val imgUrl = sku.skuImgUrl?.toString() ?: ""
                    if (imgUrl.isNotEmpty()) {
                        Glide.with(ivGoods).load(imgUrl).into(ivGoods)
                    }
                }
                updateSelectedAndParams() // 切换车型时刷新已选和参数
            }
            val params = GridLayout.LayoutParams()
            params.setMargins(12, 12, 12, 12)
            btn.layoutParams = params
            glSize.addView(btn)
        }
        // 颜色选项（从skuList中提取attrs字段的第一个为颜色名，去重）
        detail.skuList.forEach { sku ->
            val color = sku.attrs.split(",").firstOrNull()?.trim() ?: ""
            if (color.isNotEmpty() && !colorMap.containsKey(color)) {
                colorMap[color] = sku.skuImgUrl
            }
        }
        rgColor.removeAllViews()
        colorMap.keys.forEachIndexed { idx, colorName ->
            val radio = RadioButton(dialogView.context)
            radio.text = colorName
            radio.id = View.generateViewId()
            radio.buttonTintList = ContextCompat.getColorStateList(dialogView.context, R.color.red)
            radio.isChecked = idx == 0
            radio.setOnClickListener {
                selectedColor = colorName
                // 切换图片
                val imgUrl = colorMap[colorName]?.toString() ?: ""
                if (imgUrl.isNotEmpty()) {
                    Glide.with(ivGoods).load(imgUrl).into(ivGoods)
                }
                // 切换价格
                val sku = detail.skuList.find { it.attrs.split(",").firstOrNull()?.trim() == selectedColor && it.skuName == selectedCarName }
                if (sku != null) {
                    tvPrice.text = "￥${sku.purchasePrice}"
                }
                updateSelectedAndParams() // 切换颜色时刷新已选和参数
            }
            rgColor.addView(radio)
        }
        // 默认图片和价格
        val defaultImgUrl = colorMap[selectedColor]
        if (!defaultImgUrl.isNullOrEmpty()) {
            Glide.with(ivGoods).load(defaultImgUrl).into(ivGoods)
        } else {
            Glide.with(ivGoods).load(detail.posterUll.firstOrNull()).into(ivGoods)
        }
        // 默认价格
        val defaultSku = detail.skuList.find { it.attrs.split(",").firstOrNull()?.trim() == selectedColor }
        if (defaultSku != null) {
            tvPrice.text = "￥${defaultSku.purchasePrice}"
        } else {
            tvPrice.text = "￥${detail.purchasePrice}"
        }

        tvCode.text = "编号：${detail.code}"

        // 数量选择
        var count = 1
        tvCount.text = count.toString()
        ivMinus.setOnClickListener {
            if (count > 1) {
                count--
                tvCount.text = count.toString()
                updateSelectedAndParams() // 数量减少时刷新已选和参数
            }
        }
        ivPlus.setOnClickListener {
            count++
            tvCount.text = count.toString()
            updateSelectedAndParams() // 数量增加时刷新已选和参数
        }

        // 关闭
        ivClose.setOnClickListener { goodsDialog?.dismiss() }

        // 加入购物车/立即购买
        btnAddCart.setOnClickListener {
            // 找到选中的sku
            val sku = detail.skuList.find { sku ->
                val color = sku.attrs.split(",").firstOrNull()?.trim() ?: ""
                sku.skuName == selectedCarName && color == selectedColor
            }
            LoggerUtils.d("addCart", "car=$selectedCarName color=$selectedColor sku=$sku")
            if (sku != null) {
                val addShopModel = AddShopModel(
                    goodsCode = detail.code,
                    goodsId = detail.id,
                    goodsName = detail.title,
                    goodsSkuCode = sku.skuCode,
                    goodsSkuId = sku.id,
                    goodsSkuName = sku.skuName,
                    number = count
                )
                viewModel.intents.trySend(ShopIntent.AddShop(addShopModel))
                // 直接更新主页评论区的已选和参数字段
                val commentView = binding.sectionComment.getChildAt(0)
                commentView?.findViewById<TextView>(R.id.tv_type)?.text = "$selectedColor / $selectedCarName "
                commentView?.findViewById<TextView>(R.id.tv_detail)?.text = sku.goodsDesc ?: ""
                // 在showGoodsSpecDialog外部，onCreate或ShopDetailSuccess后，设置参数右箭头点击事件
                val imgFow = commentView.findViewById<ImageView>(R.id.img_fow)
                imgFow?.setOnClickListener {
                    // 获取当前选中参数
                    val typeText = commentView.findViewById<TextView>(R.id.tv_type)?.text?.toString() ?: ""
                    val carColor = typeText.split("/").map { it.trim() }
                    val selectedColor = carColor.getOrNull(0) ?: ""
                    val selectedCarName = carColor.getOrNull(1) ?: ""
                    val sku = (commentView.findViewById<TextView>(R.id.tv_detail)?.tag as? String)
                        ?: detail.skuList.find { sku ->
                            val color = sku.attrs.split(",").firstOrNull()?.trim() ?: ""
                            sku.skuName == selectedCarName && color == selectedColor
                        }?.goodsDesc ?: "暂无参数"
                    // 弹窗展示参数详情
                    val dialog = BottomSheetDialog(this@ShopDetailActivity)
                    val dialogView = layoutInflater.inflate(R.layout.dialog_params_detail, null)
                    dialog.setContentView(dialogView)
                    dialogView.findViewById<TextView>(R.id.tv_param_content)?.text = sku
                    dialogView.findViewById<Button>(R.id.btn_done)?.setOnClickListener { dialog.dismiss() }
                    dialog.show()
                }
            } else {
                showMsg("未找到对应规格，请重试")
            }
            goodsDialog?.dismiss()
        }
        btnBuyNow.setOnClickListener {
            // 找到选中的sku
            val sku = detail.skuList.find { sku ->
                val color = sku.attrs.split(",").firstOrNull()?.trim() ?: ""
                sku.skuName == selectedCarName && color == selectedColor
            }
            if (sku != null) {
                ARouter.getInstance()
                    .build("/module_shop/OrderSheetActivity")
                    .withString("goodsName", detail.title)
                    .withString("goodsDesc", detail.params)
                    .withDouble("goodsPrice", sku.purchasePrice.toDouble())
                    .withInt("goodsCount", count)
                    .withString("goodsImg", sku.skuImgUrl)
                    .navigation()
            } else {
                showMsg("未找到对应规格，请重试")
            }
            goodsDialog?.dismiss()
        }

        goodsDialog?.show()
    }

    // 新增：更新购物车角标方法
    private fun updateCartBadge(count: Int?) {
        val badge = binding.tvCartCount
        if (count != null && count > 0) {
            badge.text = count.toString()
            badge.visibility = View.VISIBLE
        } else {
            badge.visibility = View.GONE
        }
    }

    // 评论Adapter实现
    class CommentAdapter(private val comments: List<CommentRecord>) : RecyclerView.Adapter<CommentAdapter.ViewHolder>() {
        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val ivHead: ImageView = itemView.findViewById(R.id.ic_plp)
            val tvName: TextView = itemView.findViewById(R.id.comment_tv)
            val tvContent: TextView = itemView.findViewById(R.id.comment_des)
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_shop_comment, parent, false)
            return ViewHolder(view)
        }
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val comment = comments[position]
            // 头像
            val headImgUrl = comment.headImg?.toString()
            if (!headImgUrl.isNullOrEmpty() && headImgUrl != "null") {
                Glide.with(holder.itemView.context).load(headImgUrl).into(holder.ivHead)
            } else {
                holder.ivHead.setImageResource(R.drawable.ic_person)
            }
            // 用户名
            holder.tvName.text = comment.createName
            // 评论内容
            holder.tvContent.text = comment.content
        }
        override fun getItemCount() = comments.size
    }
}
